<template>
    <el-card>
        <el-row :gutter="20" class="header">
            <el-col :span="7">
                <el-input placeholder="请输入健康套餐名称..." v-model="queryForm.query" clearable></el-input>
            </el-col>
            <el-button type="primary" :icon="Search" @click="initProductHealthList">搜索</el-button>
            <el-button type="primary" :icon="DocumentAdd" @click="handleDialogValue()">添加健康套餐</el-button>
            <el-button type="danger" :icon="Delete" @click="handleDeletes()">批量删除</el-button>
        </el-row>
        <el-table  :data="tableData" @selection-change="handleSelectionChange"
                   stripe style="width: 100%" :header-cell-style="{backgroundColor:'aliceblue',color: '#666'}">
            <el-table-column type="selection" width="55" />
          <el-table-column prop="healthName" label="健康套餐名称" width="200" fixed />
          <el-table-column prop="image" label="套餐图片" width="150" align="center">
            <template v-slot="scope">
              <img :src="getServerUrl()+'/image/healthImgs/'+scope.row.image" width="80" height="80"/>
            </template>
          </el-table-column>
          <el-table-column prop="calculatedPrice" label="套餐价格" width="100" />

          <el-table-column prop="hot" label="热卖？" width="100" align="center" >
            <template v-slot="{row}">
              <el-switch v-model="row.isHot" @change="hotChangeHandle(row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="套餐介绍"  width="400" />
          <el-table-column prop="discount" label="折扣"  width="400" />

          <el-table-column prop="action" label="操作" width="450"  fixed="right">
                <template v-slot="scope">
                  <el-button type="success" @click="handleImageDialogValue(scope.row)">更换图片</el-button>
                    <el-button type="primary" :icon="Edit" @click="handleDialogValue(scope.row.id)"/>
                    <el-button type="danger" :icon="Delete" @click="handleDelete(scope.row.id)"/>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                v-model:currentPage="queryForm.pageNum"
                v-model:page-size="queryForm.pageSize"
                :page-sizes="[10, 20, 30, 40,50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
    </el-card>
    <Dialog v-model="dialogVisible" :dialogVisible="dialogVisible" :id="id" :dialogTitle="dialogTitle" @initProductHealthList="initProductHealthList"></Dialog>
    <ImageDialog v-model="imageDialogVisible" :imageDialogValue="imageDialogValue" @initProductHealthList="initProductHealthList"></ImageDialog>

</template>

<script setup>
import { Search ,Delete,DocumentAdd,Edit } from '@element-plus/icons-vue'
import {ref, watch} from 'vue'
import axios ,{ getServerUrl }from "@/util/axios";
import { ElMessage, ElMessageBox } from 'element-plus'
import Dialog from './components/dialog'
import ImageDialog from './components/imageDialog'

    const queryForm=ref({
        query:'',
        pageNum:1,
        pageSize:10,
        ids:[]
    })

    const total=ref(0)

    const tableData = ref([])

    const dialogVisible=ref(false)

    const dialogTitle=ref('')

    const id=ref(-1)
    const imageDialogVisible=ref(false)
    const imageDialogValue=ref({})
const initProductHealthList = async () => {
  const res = await axios.post("admin/productHealth/list", queryForm.value);
  // 计算每个套餐的价格
  tableData.value = res.data.productHealthList.map(item => {
    const totalPrice = item.productHealthItems.reduce((sum, healthItem) => {
      return sum + healthItem.product.price;
    }, 0);
    // 计算最终价格乘以折扣并格式化为两位小数
    item.calculatedPrice = (totalPrice * item.discount).toFixed(2);

    return item;
  });

  total.value = res.data.total;

}

    initProductHealthList();
const handleDialogValue = async (productHealthId) => {
  if (productHealthId) {
    id.value = productHealthId;
    dialogTitle.value = "健康套餐修改";
    dialogVisible.value = true;
  } else {
    id.value = -1;
    dialogTitle.value = "健康套餐添加";
    dialogVisible.value = true;
  }
};





const handleSizeChange=(pageSize)=>{
        queryForm.value.pageNum=1;
        queryForm.value.pageSize=pageSize;
        initProductHealthList();
    }

    const handleCurrentChange=(pageNum)=>{
        queryForm.value.pageNum=pageNum;
        initProductHealthList();
    }


const handleImageDialogValue=(row)=>{
  imageDialogVisible.value=true
  imageDialogValue.value=JSON.parse(JSON.stringify(row))
}

    const handleDelete=(id,status)=>{
        ElMessageBox.confirm(
            '您确定要删除这条记录吗?',
            '系统提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async() => {
                let res=await axios.get('admin/productHealth/delete/'+id)
                if(res.data.code==0){
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    initProductHealthList();
                }else{
                    ElMessage({
                        type: 'error',
                        message: res.data.msg,
                    })
                }

            })
            .catch(() => {

            })
    }
    const handleSelectionChange = (rows) => {
        queryForm.value.ids = rows.map(v => v.id)
        console.log("ids", queryForm.value.ids)
    }

    const handleDeletes = async () => {
        if (queryForm.value.ids.length === 0) {
            ElMessage({
                type: 'warning',
                message: '请选择要删除的健康套餐',
            })
            return
        }

        ElMessageBox.confirm(
            '您确定要删除选中的记录吗？',
            '系统提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async () => {
            try {
                // 使用 POST 方法并传递请求体
                let res = await axios.post('admin/productHealth/deleteBatch', queryForm.value.ids)
                if (res.data.code == 0) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    initProductHealthList()
                } else {
                    ElMessage({
                        type: 'error',
                        message: res.data.msg,
                    })
                }
            } catch (error) {
                ElMessage({
                    type: 'error',
                    message: '请求失败，请稍后重试',
                })
            }
        }).catch(() => { })
    }
const hotChangeHandle=async (row) => {
  let res=await axios.get("admin/productHealth/updateHot/"+row.id+"/state/"+row.isHot);
  if(res.data.code==0){
    ElMessage({
      type:'success',
      message: '执行成功~',
    })
  }else {
    ElMessage({
      type: 'error',
      message: res.data.msg,
    })
    initProductHealthList();
  }
}

</script>

<style lang="scss" scoped>

    .header{
        padding-bottom: 16px;
        box-sizing: border-box;
    }

    .el-pagination{
        padding-top: 15px;
        box-sizing: border-box;
    }



</style>